package org.freez4.spring.configuration.metadata;

import org.freez4.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 基于 Java 注解的 YAML 外部化配置示例。
 * 
 * @author 阿坤同学
 * @date 2024/1/15 5:02 PM
 */
@PropertySource(
        name = "yamlPropertySource",
        value = "classpath:/META-INF/user.yaml",
        factory = YamlPropertySourceFactory.class)
public class AnnotatedYamlPropertySourceDemo {

    private static final Logger logger = Logger.getLogger(AnnotatedYamlPropertySourceDemo.class.getName());


    /**
     * 读取yaml配置创建User Bean。
     *
     * @param id   用户id
     * @param name 用户名称
     * @param age  用户年龄
     * @return user bean
     * @author 阿坤同学
     * @date 2024/1/15 4:43 PM
     */
    @Bean
    public User user(@Value("${user.id}") Integer id,
                     @Value("${user.name}") String name,
                     @Value("${user.age}") Integer age) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        return user;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        // 注册当前类作为 Configuration Class
        context.register(AnnotatedYamlPropertySourceDemo.class);
        // 启动 Spring 应用上下文
        context.refresh();
        // 获取 Map YAML 对象
        User user = context.getBean("user", User.class);
        logger.log(Level.INFO, () -> "user bean:" + user);
        // 关闭 Spring 应用上下文
        context.close();
    }
}